package com.kye.express.business.deposit_recharge.online;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.ActivityRechargeOnlineBinding;
import com.kye.express.utils.ActivityManager;
import com.kye.express.utils.DateTimeUtils;
import com.kye.express.utils.InputUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.utils.pay.OnPayStatusListener;
import com.kye.express.utils.pay.OnlinePayUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.deposit.ResultJudgeLegalMoneyBean;
import com.kye.model.bean.event.EventFactory;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 预存运费-充值(线上) Activity
 * <p>
 * Created by SkyYu on 2018/1/18
 */
public class RechargeOnlineActivity extends BaseToolbarActivity implements RechargeOnlineContract.RechargeOnlineView {

    private static final String TAG = RechargeOnlineActivity.class.getSimpleName();

    private ActivityRechargeOnlineBinding mBinding;
    private RechargeOnlineContract.RechargeOnlinePresenter mPresenter;

    private User mUserInfo;
    private Dialog mDialog;

    private String mCurMoney;
    private String mCurPay;
    private String mCurInput;

    public static void startActivity() {
        ActivityManager.getInstance().getCurrentActivity().startActivity(new Intent(ActivityManager.getInstance().getCurrentActivity(), RechargeOnlineActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mPresenter) {
            mPresenter.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            InputUtils.hideSoftInput(RechargeOnlineActivity.this);
            if(mCurInput.equals("keyboard")){
                mCurMoney = mBinding.edittextRechargeOnlineMoney.getText().toString().trim();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initView() {
        initDataBinding();
        initTitle();
    }

    private void initDataBinding() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_recharge_online);
    }

    private void initTitle() {
        setUpToolbar(mBinding.toolbarRechargeOnline);
        setTitle(R.string.depositfreight_rechange);
    }

    private void initData() {
        initPresenter();
        setDefaultPay();
    }

    private void initPresenter() {
        mPresenter = new RechargeOnlineContract.RechargeOnlinePresenter();
        mPresenter.bind(this);
    }

    private void setDefaultPay() {
        mCurMoney = "0";
        mCurPay = "微信支付";
        mCurInput = "";
    }

    private void initEvent() {
        RxView.clicks(mBinding.textviewRechargeOnlineDelete)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) ->
                        mBinding.relativelayoutRechargeOnlineHine.setVisibility(View.GONE)
                );

        RxView.clicks(mBinding.buttonRechargeOnline1000)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.edittextRechargeOnlineMoney.setText("");
                    mBinding.edittextRechargeOnlineMoney.clearFocus();
                    mBinding.edittextRechargeOnlineMoney.setCursorVisible(false);
                    mBinding.buttonRechargeOnline1000.setSelected(true);
                    mBinding.buttonRechargeOnline2000.setSelected(false);
                    mBinding.buttonRechargeOnline3000.setSelected(false);
                    mBinding.buttonRechargeOnline5000.setSelected(false);
                    mCurMoney = "1000";
                    mCurInput = "button";
                });

        RxView.clicks(mBinding.buttonRechargeOnline2000)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.edittextRechargeOnlineMoney.setText("");
                    mBinding.edittextRechargeOnlineMoney.clearFocus();
                    mBinding.edittextRechargeOnlineMoney.setCursorVisible(false);
                    mBinding.buttonRechargeOnline1000.setSelected(false);
                    mBinding.buttonRechargeOnline2000.setSelected(true);
                    mBinding.buttonRechargeOnline3000.setSelected(false);
                    mBinding.buttonRechargeOnline5000.setSelected(false);
                    mCurMoney = "2000";
                    mCurInput = "button";
                });

        RxView.clicks(mBinding.buttonRechargeOnline3000)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.edittextRechargeOnlineMoney.setText("");
                    mBinding.edittextRechargeOnlineMoney.clearFocus();
                    mBinding.edittextRechargeOnlineMoney.setCursorVisible(false);
                    mBinding.buttonRechargeOnline1000.setSelected(false);
                    mBinding.buttonRechargeOnline2000.setSelected(false);
                    mBinding.buttonRechargeOnline3000.setSelected(true);
                    mBinding.buttonRechargeOnline5000.setSelected(false);
                    mCurMoney = "3000";
                    mCurInput = "button";
                });

        RxView.clicks(mBinding.buttonRechargeOnline5000)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    mBinding.edittextRechargeOnlineMoney.setText("");
                    mBinding.edittextRechargeOnlineMoney.clearFocus();
                    mBinding.edittextRechargeOnlineMoney.setCursorVisible(false);
                    mBinding.buttonRechargeOnline1000.setSelected(false);
                    mBinding.buttonRechargeOnline2000.setSelected(false);
                    mBinding.buttonRechargeOnline3000.setSelected(false);
                    mBinding.buttonRechargeOnline5000.setSelected(true);
                    mCurMoney = "5000";
                    mCurInput = "button";
                });

        RxTextView.editorActionEvents(mBinding.edittextRechargeOnlineMoney)
                .compose(this.bindToLifecycleDestroy())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.computation())
                .filter((textViewEditorActionEvent) ->
                        !TextUtils.isEmpty(mBinding.edittextRechargeOnlineMoney.getText().toString())
                )
                .map((textViewEditorActionEvent) ->
                        mBinding.edittextRechargeOnlineMoney.getText().toString().trim()
                )
                .doOnNext((string) ->
                        Logger.d("input : " + string)
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String queryData) {
                        Logger.d(queryData);
                        mCurMoney = mBinding.edittextRechargeOnlineMoney.getText().toString().trim();
                        InputUtils.hideSoftInput(RechargeOnlineActivity.this);
                    }

                    @Override
                    public void onError(Throwable e) {
                        InputUtils.hideSoftInput(RechargeOnlineActivity.this);
                    }

                    @Override
                    public void onComplete() {
                    }
                });

        RxTextView.editorActionEvents(mBinding.edittextRechargeOnlineRemark)
                .compose(this.bindToLifecycleDestroy())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(Schedulers.computation())
                .filter((textViewEditorActionEvent) ->
                        !TextUtils.isEmpty(mBinding.edittextRechargeOnlineRemark.getText().toString())
                )
                .map((textViewEditorActionEvent) ->
                        mBinding.edittextRechargeOnlineRemark.getText().toString()
                )
                .doOnNext((string) ->
                        Logger.d("input : " + string)
                )
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String queryData) {
                        Logger.d(queryData);
                        InputUtils.hideSoftInput(RechargeOnlineActivity.this);
                    }

                    @Override
                    public void onError(Throwable e) {
                        InputUtils.hideSoftInput(RechargeOnlineActivity.this);
                    }

                    @Override
                    public void onComplete() {
                        InputUtils.hideSoftInput(RechargeOnlineActivity.this);
                    }
                });

        RxTextView.textChanges(mBinding.edittextRechargeOnlineMoney)
                .compose(bindToLifecycleDestroy())
                .map(TextUtils::isEmpty)
                .subscribe(isEmpty -> {
                    if(!isEmpty){
                        mBinding.edittextRechargeOnlineMoney.setCursorVisible(true);
                        mBinding.buttonRechargeOnline1000.setSelected(false);
                        mBinding.buttonRechargeOnline2000.setSelected(false);
                        mBinding.buttonRechargeOnline3000.setSelected(false);
                        mBinding.buttonRechargeOnline5000.setSelected(false);
                        mCurInput = "keyboard";
                    }
                });

        // Warning：用RxView.clicks的方式导致切换SVG图片无效果，故用原生寻找ID方式来解决
        RelativeLayout mLayoutWeChat = findViewById(R.id.relativelayout_online_wetchat_select);
        RelativeLayout mLayoutAlipay = findViewById(R.id.relativelayout_online_alipay_select);
        @SuppressLint("WrongViewCast")
        AppCompatImageView mImageViewWeChat = findViewById(R.id.imageview_online_wetchat_select);
        @SuppressLint("WrongViewCast")
        AppCompatImageView mImageViewAlipay = findViewById(R.id.imageview_online_alipay_select);
        mLayoutWeChat.setOnClickListener((View) -> {
            mImageViewWeChat.setImageResource(R.drawable.icon_recharge_online_success);
            mImageViewAlipay.setImageResource(R.drawable.icon_recharge_select);
            mCurPay = "微信支付";
        });
        mLayoutAlipay.setOnClickListener((View) -> {
            mImageViewAlipay.setImageResource(R.drawable.icon_recharge_online_success);
            mImageViewWeChat.setImageResource(R.drawable.icon_recharge_select);
            mCurPay = "支付宝";
        });

        RxView.clicks(mBinding.buttonOnlineGo)
                .compose(this.bindToLifecycleDestroy())
                .compose(new DebounceObservableTransformer<>())
                .subscribe((Object) -> {
                    if (!check()) return;
                    showProgressDialog();
                    mPresenter.requestToJudgeLegalMoney(mCurMoney);
                });

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    private boolean check() {
        if (StringUtils.isNullOrEmpty(mCurMoney)) {
            ToastManager.show(this, "请输入充值金额");
            return false;
        }
        int mCurMoneyInt = Integer.parseInt(mCurMoney);
        if (mCurMoneyInt == 0) {
            ToastManager.show(this, "充值金额不能为0");
            return false;
        }
        if (mCurMoneyInt < 1000) {
            ToastManager.show(this, "最低充值金额为1000元");
        }
        if (mCurMoneyInt > 200000) {
            ToastManager.show(this, "单次充值金额不超过20万");
            return false;
        }
        if (mCurMoneyInt % 100 != 0) {
            ToastManager.show(this, "充值金额且为100的整数倍");
            return false;
        }
        return true;
    }

    private void showProgressDialog() {
        mDialog = KyeProgressDialog.show(this, mDialog);
        KyeProgressDialog.show(this, mDialog);
    }

    public void closeProgressDialog() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onLoadUserInfo(User user) {
        if (user == null || !user.isLogin()) {
            ToastManager.show(this, "请先登录");
            LoginActivity.startActivity(this);
        } else {
            mUserInfo = user;
            mBinding.setData(user);
        }
    }

    @Override
    public void onJudgeLegalMoneySuccess(OpenApiResult<ResultJudgeLegalMoneyBean> bean) {
        if (bean != null) {
            if (bean.getCode() == Constants.ResponseCode_SUCCESS) {
                if (bean.getData().isIsLegal()) {
                    requestToPay();
                } else {
                    closeProgressDialog();
                    Logger.d("预存运费金额不合法");
                }
            } else {
                closeProgressDialog();
                ToastManager.show(this, bean.getMsg());
            }
        } else {
            closeProgressDialog();
            Logger.d(TAG + " - onJudgeLegalMoneySuccess - bean is null");
        }
    }

    @Override
    public void onJudgeLegalMoneyApiError(OpenApiResult<ResultJudgeLegalMoneyBean> result, int code, String msg) {
        closeProgressDialog();
        ToastManager.show(this, msg);
        Logger.d(TAG + " - onJudgeLegalMoneyApiError - result:" + result + ",code:" + code + ",msg:" + msg);

    }

    @Override
    public void onJudgeLegalMoneyOtherError(Throwable e) {
        closeProgressDialog();
        ToastManager.show(this, getString(R.string.common_net_error));
        Logger.d(TAG + " - onJudgeLegalMoneyOtherError : " + e.getMessage());
        e.printStackTrace();
    }

    private void requestToPay() {
        String money = mCurMoney;
        DecimalFormat df = new DecimalFormat("######0");   // 四色五入转换成整数
        String centsMoney = df.format(Double.parseDouble(money) * 100);   // 因微信的支付是按分来计算所以要乘以100
        String remark = mBinding.edittextRechargeOnlineRemark.getText().toString();
        switch (mCurPay) {
            case "微信支付":
                OnlinePayUtils.getInstance().preDepositFreigPayByWechat(this, mUserInfo, centsMoney, remark, new OnPayStatusListener() {
                    @Override
                    public void onPaySuccess(Map<String, String> response) {
                        Logger.d(TAG + " requestToPay - 微信支付onPaySuccess - response:" + response);
                        closeProgressDialog();
                        // 和支付宝不一样，这步走完然后等待onWechatPayCallBack函数的回调通知
                    }

                    @Override
                    public void onPayFail(Map<String, String> errMap, String error) {
                        Logger.d(TAG + " requestToPay - 微信支付onPayFail - " + "errMap:" + errMap + ",error:" + error);
                        closeProgressDialog();
                    }
                });
                break;
            case "支付宝":
                OnlinePayUtils.getInstance().preDepositFreigByAli(this, centsMoney, mUserInfo, new OnPayStatusListener() {
                    @Override
                    public void onPaySuccess(Map<String, String> response) {
                        // 支付宝和微信不一样，在这里就是支付结果的成功和失败回调
                        Logger.d(TAG + " requestToPay - 支付宝onPaySuccess - response:" + response);
                        closeProgressDialog();
                        String mCurDate = DateTimeUtils.getStringDate(System.currentTimeMillis(), Constants.CURRENT_TIME_ALL);
                        RechargeOnlineSuccessActivity.startActivity(mCurMoney, mCurDate, mCurPay, mUserInfo.getPhone());
                        finish();
                    }

                    @Override
                    public void onPayFail(Map<String, String> errMap, String error) {
                        Logger.d(TAG + " requestToPay - 支付宝onPayFail - " + "errMap:" + errMap + ",error:" + error);
                        closeProgressDialog();
                        ToastManager.show(RechargeOnlineActivity.this, error);
                    }
                });
                break;
            default:
                break;
        }
    }

    /**
     * 来自微信支付【WXPayEntryActivity】页面的支付结果回调，通过EventBus通知
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatPayCallBack(EventFactory.OnWechatPayEvent onWechatPayEvent) {
        closeProgressDialog();
        if (onWechatPayEvent != null) {
            if (BaseResp.ErrCode.ERR_OK == onWechatPayEvent.code) {
                ToastManager.show(this,"充值成功");
                String mCurDate = DateTimeUtils.getStringDate(System.currentTimeMillis(), Constants.CURRENT_TIME_ALL);
                RechargeOnlineSuccessActivity.startActivity(mCurMoney, mCurDate, mCurPay, mUserInfo.getPhone());
                finish();
            } else {
                ToastManager.show(this, onWechatPayEvent.msg);
            }
        } else {
            Logger.d(TAG + " - onWechatPayCallBack - onWechatPayEvent is null");
        }
    }
}